package com.example.jeson.stocktest.mvp;

import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;
import android.util.Log;

import com.example.jeson.stocktest.entity.MessageList;
import com.example.jeson.stocktest.entity.Stock;
import com.example.jeson.stocktest.util.HSJsonUtil;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

/**
 * @author jeson
 */
public class MainPresenter {
    private final static String FILE_NAME = "data.json";
    private final static String BASE_URL = "https://bao.wallstreetcn.com/q/quote/v1/real";
    private final static int TIMER_COUNT = 3000;


    private IMainView myView;
    private MyThread mTimerThread = new MyThread();

    private List<MessageList.Messages> myMessageList = new ArrayList<>();
    private HashMap<String, Stock> mStockMap = new HashMap<>();


    public MainPresenter(IMainView iMainView) {
        this.myView = iMainView;
    }

    public List<MessageList.Messages> getMyMessageList() {
        return myMessageList;
    }

    public HashMap<String, Stock> getmStockMap() {
        return mStockMap;
    }

    /**
     * 从JSON 中解析出message 列表
     *
     * @param ctx
     * @return
     */
    public void getListFromAssets(Context ctx) {

        AssetManager assetManager = ctx.getAssets();
        try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(FILE_NAME)));

            Gson gson = new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
                    .create();
            MessageList messageList = gson.fromJson(bf, MessageList.class);
            myMessageList = messageList.Messages;

        } catch (IOException e) {
            e.printStackTrace();
        }

        if (myMessageList != null) {
            myView.initView();
            //getHTTPStock();
            mTimerThread.start();
        }
    }

    /**
     * 结束刷新线程
     */
    public void stopThread() {
        if (mTimerThread != null) ;
        {
            mTimerThread.bRun = false;
        }
    }

    /**
     * 获取股票信息
     */
    public void getHTTPStock() {
        HashMap<String, String> allStock = new HashMap<>();
        for (MessageList.Messages msg : myMessageList) {
            if (msg.Stocks != null && !msg.Stocks.isEmpty()) {
                for (MessageList.Messages.Stocks stocks : msg.Stocks) {
                    allStock.put(stocks.Symbol, stocks.Name);
                }
            }
        }

        OkHttpUtils.get().url(BASE_URL)
                .addParams("en_prod_code", StringUtils.join(allStock.keySet(), ","))
                .addParams("fields", "prod_name,px_change,last_px,px_change_rate,trade_status")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                ArrayList<Stock> mList = HSJsonUtil.getRealStockList(response, "snapshot");
                boolean bHasTrade = false;
                for (Stock stock : mList) {
                    if (mStockMap.put(stock.symbol, stock) != null) {
                        Log.d("Stock", stock.trade_status + ";" + stock.symbol + ";" + stock.px_change_rate);
                    }
                    if (TextUtils.equals(stock.trade_status, Stock.TRADE)) {
                        bHasTrade = true;
                    }
                }
                if (bHasTrade) {
                    myView.updateStocks();
                }

            }
        });

    }

    /**
     * @author jeson
     */
    class MyThread extends Thread {
        public boolean bRun = true;

        @Override
        public void run() {
            while (bRun) {
                getHTTPStock();
                try {
                    Thread.sleep(TIMER_COUNT);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }


}
